package com.example.springsecurity.security;

import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.common.CommonResult;
import com.example.springsecurity.enums.ErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author wuancheng
 * @date 2024/6/19 18:14
 * @description 认证失败处理
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint{

    /**
     * 认证失败处理返回
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        CommonResult commonResult = CommonResult.failed(ErrorCode.NO_LOGIN.getErrorCode(), ErrorCode.NO_LOGIN.getErrorDesc());
        response.getWriter().println(JSONObject.toJSONString(commonResult));
    }
}
